package com.lemurian.bankdata.bean;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.lemurian.bankdata.bean.base.BaseDaoHibernate;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.entity.Client;
import com.lemurian.entity.ClientCertificate;

@Repository
public class ClientCertificateDAO extends BaseDaoHibernate<ClientCertificate> {
	
	private BankDataLogger log = BankDataLogger.getLogger(ClientCertificateDAO.class.getName());

	public List<ClientCertificate> getByClientId(Client client) {
		List<ClientCertificate> list = null;
		
		try {
			
			Criteria criteria = getSession().createCriteria(ClientCertificate.class);
			
			criteria.createCriteria("certificateType", "certificateType", Criteria.INNER_JOIN);
			
			criteria.add(Restrictions.eq("client", client));
			
			criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
			
			list = criteria.list();
			
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		return list;
	}
	
	@Override
	public ClientCertificate load(int id){
		ClientCertificate entity = null;
		try {
			Criteria criteria = getSession().createCriteria(ClientCertificate.class);
			
			criteria.createCriteria("certificateType", "certificateType", Criteria.INNER_JOIN);
			
			criteria.add(Restrictions.eq("id", id));
			
			criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
			
			entity = (ClientCertificate) criteria.uniqueResult();
		} catch(Throwable t){
			t.printStackTrace();
		}
		return entity;
	}
	
	@Override
	public List<ClientCertificate> findByCriteria(Order order, Criterion... criterion) {
		try {
			log.info("Get Overide");
			Criteria criteria = getSession().createCriteria(ClientCertificate.class);
			criteria.createCriteria("certificateType", "certificateType", Criteria.INNER_JOIN);
			criteria.createCriteria("certificateType.parent", "parent", Criteria.INNER_JOIN);
			criteria.setCacheable(true);
			for (Criterion c : criterion) {
				criteria.add(c);
			}
			if (order!=null) criteria.addOrder(order);
			List<ClientCertificate> list = criteria.list();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}